
import _ from 'lodash'

function has (value, checkCodes, isall) {
  let access = false
  // 字符串
  if (_.isString(value)) {
    // 隐藏功能权限功能
    if(value.split('/').length>3){
      access = true
    }
    if (checkCodes.includes(value)) {
      access = true
    }
    // 数组
  } else if (_.isArray(value)) {
    if (_.isEmpty(value)) {
      // 空数组直接认为无权限
      access = false
    } else {
      if (isall) {
        // 全部匹配才认为通过
        access = value.every(i => checkCodes.includes(i))
      } else {
        access = value.some(i => checkCodes.includes(i))
      }
    }
  }

  return access
}
export default {
  install (Vue) {
    Vue.directive('permission', {
      inserted: async function (el, binding, vnode) {
        let checkCodes = JSON.parse(localStorage.getItem('menuPermission'))
        if (!has(binding.value, checkCodes, binding.modifiers.all)) {
          // 直接删除dom 可能布局错位
          el.parentNode.removeChild(el)
          // css 放置到不可见 ，布局不错位
          // el.style.transform = 'translateX(9999999px)'
        }
      }
    })
    Vue.prototype.hasPermissions = permissions => {
      let checkCodes = JSON.parse(localStorage.getItem('menuPermission'))

      return has(permissions, checkCodes)
    }
  }
}
